package com.glSto.rep;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.io.IOException;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class TargetApiResponse {
    private int code; // 状态码
    private String msg; // 提示信息
    private Data data; // 业务数据（成功时是对象，失败时是字符串）
    private String status; // 状态标识
    private String requestId; // 请求唯一ID
    private String formDataId; // 表单数据ID

    @lombok.Data
    @JsonDeserialize(using = DataDeserializer.class) // 仍使用自定义反序列化器，但修复逻辑
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class Data {
        private String id; // 物料记录ID
        private String materialCode; // 物料编码
        private String materialName; // 物料名称
        private String uom; // 单位
        private String price; // 价格
        private String materialGroup; // 物料组
        private String shopGroup; // 采购组
        private String sourceMaterialId; // 源物料ID
        private String title; // 标题
        private String companyId; // 公司ID
        private String companyCode; // 公司代码
        private String companyName; // 公司名称
        private String bizAreaId; // 业务区域ID
        private String tableName; // 表名
        private Integer orderNum; // 排序号
        private Integer status; // 状态
        private String memo; // 备注
        private String regPosiId; // 注册职位ID
        private String epsProjId; // 项目ID
        private String epsProjCode; // 项目代码
        private String epsProjName; // 项目名称
        private String recycleHumId; // 回收人ID
        private String apprHumId; // 审批人ID
        private String apprHumName; // 审批人姓名
        private String apprDate; // 审批日期
        private String ownProjId; // 所属项目ID
        private String ownProjName; // 所属项目名称
        private String createHum; // 创建人
        private String createHumId; // 创建人ID
        private String createTime; // 创建时间
        private String updateHum; // 更新人
        private String updateHumId; // 更新人ID
        private String updateTime; // 更新时间
        private String regDeptId; // 注册部门ID
    }

    // 修复后的自定义反序列化器：手动解析字段，避免递归
    public static class DataDeserializer extends JsonDeserializer<Data> {
        @Override
        public Data deserialize(JsonParser p, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {

            if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
                // 错误情况：Data字段是字符串（如错误信息），仅设置id
                Data data = new Data();
                data.setId(p.getText()); // 假设字符串是id或错误标识
                return data;
            } else if (p.getCurrentToken() == JsonToken.START_OBJECT) {
                // 成功情况：Data是对象，手动解析每个字段，避免递归调用
                JsonNode node = p.getCodec().readTree(p); // 读取整个对象节点
                Data data = new Data();

                // 手动提取字段并设置到Data对象（按需映射所有字段）
                data.setId(readString(node, "id"));
                data.setMaterialCode(readString(node, "materialCode"));
                data.setMaterialName(readString(node, "materialName"));
                data.setUom(readString(node, "uom"));
                data.setPrice(readString(node, "price"));
                data.setMaterialGroup(readString(node, "materialGroup"));
                data.setShopGroup(readString(node, "shopGroup"));
                data.setSourceMaterialId(readString(node, "sourceMaterialId"));
                data.setTitle(readString(node, "title"));
                data.setCompanyId(readString(node, "companyId"));
                data.setCompanyCode(readString(node, "companyCode"));
                data.setCompanyName(readString(node, "companyName"));
                data.setBizAreaId(readString(node, "bizAreaId"));
                data.setTableName(readString(node, "tableName"));
                data.setOrderNum(readInteger(node, "orderNum"));
                data.setStatus(readInteger(node, "status"));
                data.setMemo(readString(node, "memo"));
                data.setRegPosiId(readString(node, "regPosiId"));
                data.setEpsProjId(readString(node, "epsProjId"));
                data.setEpsProjCode(readString(node, "epsProjCode"));
                data.setEpsProjName(readString(node, "epsProjName"));
                data.setRecycleHumId(readString(node, "recycleHumId"));
                data.setApprHumId(readString(node, "apprHumId"));
                data.setApprHumName(readString(node, "apprHumName"));
                data.setApprDate(readString(node, "apprDate"));
                data.setOwnProjId(readString(node, "ownProjId"));
                data.setOwnProjName(readString(node, "ownProjName"));
                data.setCreateHum(readString(node, "createHum"));
                data.setCreateHumId(readString(node, "createHumId"));
                data.setCreateTime(readString(node, "createTime"));
                data.setUpdateHum(readString(node, "updateHum"));
                data.setUpdateHumId(readString(node, "updateHumId"));
                data.setUpdateTime(readString(node, "updateTime"));
                data.setRegDeptId(readString(node, "regDeptId"));

                return data;
            }

            return null;
        }

        // 工具方法：从JsonNode读取字符串（处理null）
        private String readString(JsonNode node, String fieldName) {
            JsonNode fieldNode = node.get(fieldName);
            return (fieldNode != null && !fieldNode.isNull()) ? fieldNode.asText() : null;
        }

        // 工具方法：从JsonNode读取整数（处理null）
        private Integer readInteger(JsonNode node, String fieldName) {
            JsonNode fieldNode = node.get(fieldName);
            return (fieldNode != null && !fieldNode.isNull() && fieldNode.isInt()) ? fieldNode.asInt() : null;
        }
    }
}